#!/usr/bin/env python3
import os
import subprocess
import sys

def setup_environment():
    """设置正确的环境变量"""
    # 清除可能错误的环境变量
    if 'DOCKER_HOST' in os.environ and 'http+docker' in os.environ['DOCKER_HOST']:
        print("Removing invalid DOCKER_HOST environment variable")
        del os.environ['DOCKER_HOST']
    
    # 尝试检测正确的Docker socket路径
    docker_sockets = [
        '/var/run/docker.sock',
        '/run/docker.sock',
    ]
    
    for socket_path in docker_sockets:
        if os.path.exists(socket_path):
            os.environ['DOCKER_HOST'] = f'unix://{socket_path}'
            print(f"Set DOCKER_HOST to: unix://{socket_path}")
            break
    else:
        print("Warning: No Docker socket found, using TCP fallback")
        os.environ['DOCKER_HOST'] = 'tcp://127.0.0.1:2375'

def main():
    # 设置环境
    setup_environment()
    
    # 启动Flask应用
    os.environ['FLASK_APP'] = 'app.py'
    os.environ['FLASK_ENV'] = 'development'
    
    try:
        subprocess.run([sys.executable, '-m', 'flask', 'run', '--host=0.0.0.0', '--port=5000'], check=True)
    except subprocess.CalledProcessError as e:
        print(f"Flask application failed to start: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()
